<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Education;
use App\Models\Item;
use App\Models\Job;
use App\Models\Position;
use App\Models\Resume;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Redis;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;
use Validator;

class ShareController extends Controller {
	/**
	 * 申请简历
	 * @param  Request $request [description]
	 */
	public function resumeAdd(Request $request) {
		$company_id = $request->input('cid');
		$position_id = $request->input('pid');
		$position = Position::where(['id' => $position_id, 'status' => 0])->first();
		if (empty($position)) {
			return response()->json(['code' => 500, 'msg' => '参数为空或无效']);
		}
		$job = [];
		$item = [];
		$edu = [];
		$resume = $request->resume;
		if (isset($request->job)) {
			$job = $request->job;
		}
		if (isset($request->item)) {
			$item = $request->item;
		}
		if (isset($request->edu)) {
			$edu = $request->edu;
		}
		$time = time();
		$uid = $position->user_id;
		if (is_string($resume)) {
			$resume = json_decode($resume, true);
		}
		if (is_string($item)) {
			$item = json_decode($item, true);
		}
		if (is_string($job)) {
			$job = json_decode($job, true);
		}
		if (is_string($edu)) {
			$edu = json_decode($edu, true);
		}
		$resume['user_id'] = $uid;
		$resume['owner_id'] = $uid;
		$resume['company_id'] = $company_id;
		$resume['position_id'] = $position_id;
		$resume['created_at'] = $time;
		$resume['updated_at'] = $time;
		$info = [];
		if ($request->hasFile('attachment')) {
			$file = $request->file('attachment');
			if (empty($file)) {
				return response()->json(['code' => 500, 'msg' => '简历附件名称不能为空']);
			}
			if (!$request->hasFile('attachment')) {
				return response()->json(['code' => 500, 'msg' => '上传附件为空或无效']);
			}
			if (!$request->file('attachment')->isValid()) {
				return response()->json(['code' => 500, 'msg' => $file->getErrorMessage()]);
			}
			$name = $file->getClientOriginalName();
			$ext = $file->getClientOriginalExtension();
			if (!in_array(strtolower($ext), ['png', 'jpg', 'doc', 'docx', 'pdf'])) {
				return response()->json(['code' => 500, 'msg' => '只允许上传png、jpg、doc、docx、pdf格式的图片']);
			}
			if ($file->getClientSize() > (10 * 1024 * 1024)) {
				return response()->json(['code' => 500, 'msg' => '图片大小不能超过10M']);
			}
			$newFileName = md5(time() . rand(0, 10000)) . '.' . $file->getClientOriginalExtension();
			$savePath = 'attachment/' . date('Ym', time()) . '/' . $newFileName;
			$bytes = \Storage::put(
				$savePath,
				file_get_contents($file->getRealPath())
			);
			if (!\Storage::exists($savePath)) {
				return response()->json(['code' => 500, 'msg' => '上传简历附件出错,请重试']);
			}
			$path = 'storage/' . $savePath;
			$info['attachment'] = $path;
			$info['attachment_name'] = $name;
			if (!empty($info)) {
				$resume['attachment'] = $info['attachment'];
				$resume['attachment_name'] = $info['attachment_name'];
			}
		}
		$check_mobile = [];
		if (empty($resume['name']) || empty($resume['mobile'])) {
			return response()->json(['code' => 500, 'msg' => '姓名或电话不能为空']);
		}
		\Log::info('resumes' . json_encode($resume));
		\Log::info('job' . json_encode($job));
		\Log::info('item' . json_encode($item));
		\Log::info('edu' . json_encode($edu));
		$check_mobile = Resume::where(['status' => 0, 'company_id' => $company_id, 'mobile' => $resume['mobile']])->first();
		if (!empty($check_mobile)) {
			//更新简历
			$check_mobile->name = $resume['name'];
			$check_mobile->sex = $resume['sex'];
			$check_mobile->is_job = $resume['is_job'];
			$check_mobile->job_date = $resume['job_date'];
			$check_mobile->birthday = $resume['birthday'];
			$check_mobile->position = $resume['position'];
			$check_mobile->edu = $resume['edu'];
			$check_mobile->company_name = $resume['company_name'];
			$check_mobile->email = $resume['email'];
			$check_mobile->area = $resume['area'];
			$check_mobile->position_id = $position_id;
			$check_mobile->user_id = $uid;
			$check_mobile->owner_id = $uid;
			$check_mobile->company_id = $company_id;
			if (!empty($info)) {
				$check_mobile->attachment = $info['attachment'];
				$check_mobile->attachment_name = $info['attachment_name'];
			}
			$get_date_arr = [];
			$max_date = 0;
			if (!empty($job)) {
				foreach ($job as $key => $value) {
					$get_date_arr[] = $value['start_date'];
				}
				$max_date = max($get_date_arr);
			}
			$check_job = Job::where(['status' => 0, 'resume_id' => $check_mobile->id])->orderBy('start_date', 'desc')->select('id', 'start_date')->first();
			if (!empty($check_job) && $check_job->start_date >= $max_date) {
				return response()->json(['code' => 500, 'msg' => '重复简历！']);
			}
		}
		//开启事务
		DB::beginTransaction(); //新增简历
		try {
			//中间逻辑代码
			if (!empty($check_mobile)) {

				$check_mobile->save();
				$sid = $check_mobile->id;
				Job::where(['status' => 0, 'resume_id' => $sid])->update(['status' => 1]);
				Item::where(['status' => 0, 'resume_id' => $sid])->update(['status' => 1]);
				Education::where(['status' => 0, 'resume_id' => $sid])->update(['status' => 1]);
			} else {
				$sid = DB::table('resumes')->insertGetId($resume);
			}
			\Log::info('sid:' . $sid);
			if (!empty($job)) {
				foreach ($job as $key => $value) {
					$value['resume_id'] = $sid;
					$value['created_at'] = $time;
					$value['updated_at'] = $time;
					Job::insert($value);
				}
			}
			if (!empty($item)) {
				foreach ($item as $key => $va1) {
					$va1['resume_id'] = $sid;
					$va1['created_at'] = $time;
					$va1['updated_at'] = $time;
					Item::insert($va1);
				}
			}
			if (!empty($edu)) {
				foreach ($edu as $key => $va2) {
					$va2['resume_id'] = $sid;
					$va2['created_at'] = $time;
					$va2['updated_at'] = $time;
					Education::insert($va2);
				}

			}
			//更新简历基础信息
			$get_company_name = Job::where(['resume_id' => $sid, 'status' => 0])->orderBy('start_date', 'desc')->select('company_name')->first();
			$get_edu = Education::where(['resume_id' => $sid, 'status' => 0])->orderBy('start_date', 'desc')->select('edu')->first();
			$get_resume = Resume::find($sid);
			if (!empty($get_company_name) || !empty($get_edu)) {
				$get_resume->company_name = $get_company_name ? $get_company_name->company_name : '';
				$get_resume->edu = $get_edu ? $get_edu->edu : '';
				\Log::info('get_resume' . json_encode($get_resume->toArray()));
				$get_resume->save();
			}
			DB::commit();
			return $this->respond('add_ok');
		} catch (\Exception $e) {
			//接收异常处理并回滚
			\Log::info('简历批量添加：' . json_encode($e));
			DB::rollBack();
			return $this->respond('add_error');
		}
	}
	/**
	 * 发送验证码
	 * @param  Request $request
	 */
	public function sendMessage(Request $request) {
		$validator = Validator::make($request->all(), ['mobile' => 'required|regex:/^[1][0-9]{10}$/'], ['mobile.required' => '手机号不能为空',
			'mobile.regex' => '手机号格式不正确']);
		if ($validator->fails()) {
			return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
		}
		$mobile = $request->input('mobile');
		$config = Config::get('info.message_config');
		$easySms = new EasySms($config);
		$code = rand(1000, 9999);
		$redMobile = Redis::exists($mobile . 'resume_code');
		if ($redMobile) {
			Redis::del($mobile . 'resume_code');
		}
		$redTime = Redis::exists($mobile . 'resume_time');
		if ($redTime) {
			Redis::del($mobile . 'resume_time');
		}
		try {
			$result = $easySms->send($mobile, [
				'content' => '您的验证码${code}，该验证码5分钟内有效，请勿泄漏于他人！',
				'template' => 'SMS_126570108',
				'data' => [
					'code' => $code,
				],
			]);
		} catch (NoGatewayAvailableException $e) {
			return response()->json(['code' => 200, 'msg' => '短信发送失败']);
		}
		Redis::setex($mobile . 'resume_code', 300, $code);
		Redis::setex($mobile . 'resume_time', 300, time());
		if ($result['aliyun']['status'] == 'success') {
			return response()->json(['code' => 200, 'msg' => '短信发送成功']);
		} else {
			return response()->json(['code' => 400, 'msg' => '由于您操作次数过多，5分钟后再进行操作']);
		}
	}
	/**
	 * 验证码验证
	 * @param  $mobile     [请求手机号]
	 * @param  $code   [验证码]
	 */
	public function codeVerify(Request $request) {
		$mobile = $request->input('mobile');
		$postCode = $request->input('code');
		if (empty($mobile) || empty($postCode)) {
			return $this->respond('empty_error');
		}
		$nowTime = time();
		$redisCode = Redis::get($mobile . 'resume_code');
		$redisTime = Redis::get($mobile . 'resume_time');
		$timeApart = $nowTime - $redisTime;
		if ($timeApart < 0 || $timeApart > 300 || ($redisCode != $postCode)) {
			return response()->json(['code' => 500, 'msg' => '验证码错误或失效']);
		}
		Redis::del($mobile . 'resume_code');
		Redis::del($mobile . 'resume_time');
		return response()->json(['code' => 200, 'msg' => '验证成功']);
	}
	public function getWxAccessToken(Request $request) { //8125fd25face499aea90665b6e709f0e
		$url=$request->input('pageUrl');
		if(empty($url)){
			return $this->respond('empty_error');
		}
		$jssdk = new \App\Libs\Wxjsapi\Jssdk("wx6b7948da56874135", "8125fd25face499aea90665b6e709f0e",$url);
		$signPackage = $jssdk->GetSignPackage();
		return $signPackage;
	}
}
